<?php

/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */
class wms_ctl_admin_spadjustmentdoc extends desktop_controller
{
    //应收按月+客户+料品+单位【销售数量】汇总数量和金额；
    //应付快递费与服务费按月+料品+单位【销售数量】汇总数量和金额 


    function index()
    {
          
        $actions= array(
            'new' => array(
                'label' => '新建',
                'href' => 'index.php?app=wms&ctl=admin_spadjustmentdoc&act=add_spadjustmentdoc',
                    'target' => '_blank',
            ),
            'approve' => array(
                'label' => '审核',
                'submit' => 'index.php?app=wms&ctl=admin_spadjustmentdoc&act=doapprove',
            ),
            'unapprove' => array(
                'label' => '弃审',
                'submit' => 'index.php?app=wms&ctl=admin_spadjustmentdoc&act=dounapprove',
            ),
            'create' => array(
                'label' => '生成明细',
                'submit' => 'index.php?app=wms&ctl=admin_spadjustmentdoc&act=doCreate',
            ),
            'cancel' => array(
                'label' => '取消生成',
                'submit' => 'index.php?app=wms&ctl=admin_spadjustmentdoc&act=doCancel',
            ),
            'sync' => array(
                'label' => '过数同步',
                'submit' => 'index.php?app=wms&ctl=admin_spadjustmentdoc&act=doConfirm',
            ),
            'delete' => array(
                'label' => '删除',
                'submit' => 'index.php?app=wms&ctl=admin_spadjustmentdoc&act=doDelete',
            ),
        );

        $filter=array();

        $params = array(
            'title' => '店铺促销差价调整单',
            'actions' =>$actions,
            'base_filter' => $filter,
            'use_buildin_new_dialog' => false,
            'use_buildin_set_tag' => false,
            'use_buildin_recycle' => false,
            'use_buildin_export' => false ,
            'use_buildin_import' => false,
            'use_buildin_filter' => true,
            'allow_detail_popup' => true,
            'max_actions' => 8,
            'use_view_tab' => false,
            'orderBy' => 'create_time desc',
        );
        $user = kernel::single('desktop_user');
        if(!$user->has_permission('wms_ctl_admin_spadjustmentdoc'))
        {
            unset($params['actions']['new']);
            unset($params['actions']['delete']);
        }
        if(!$user->has_permission('wms_ctl_admin_spadjustmentdoc_approve'))
        {
            unset($params['actions']['approve']);
            unset($params['actions']['unapprove']);
        }
        if(!$user->has_permission('wms_ctl_admin_spadjustmentdoc_create'))
        {
            unset($params['actions']['create']);
            unset($params['actions']['cancel']);            
        }
        if(!$user->has_permission('wms_ctl_admin_spadjustmentdoc_sync'))
        {
            unset($params['actions']['sync']);
        }
        $this->finder('wms_mdl_spadjustmentdoc', $params);
    }
    //添加备货
    function add_spadjustmentdoc()
    {
        //add by ldward 20180515 改造查询
        
        $sql = 'SELECT shop_id,shop_bn,name FROM sdb_ome_shop WHERE leemantype=\'1\' ';
        $shop_datas = kernel::database()->select($sql);
        foreach ($shop_datas as $v) {
            $shop_data[$v['shop_id']] ='【'.$v['shop_bn'].'】'. $v['name'];
        }
        $this->pagedata['shop_data'] = $shop_data;
        $operator = kernel::single('desktop_user')->get_name();
        $this->pagedata['spadjustmentdoc']['inter_time'] = date('Y-m-d',time());
        $this->pagedata['spadjustmentdoc']['booked_time'] = date('Y-m-d',time());
        $this->pagedata['spadjustmentdoc']['operator'] = $operator;
        $this->pagedata['spadjustmentdoc']['sp_bn']=$this->gen_id();
        $this->singlepage('admin/spadjustmentdoc/spdoc_add.html');
    }
    
    /*
     * 生成调整单号
     *
     *
     * @return 退货单号
     */
    function gen_id(){
        $i = rand(0,9999);
        do{
            if(9999==$i){
                $i=0;
            }
            $i++;
            $sp_bn = date("YmdH").'13'.str_pad($i,6,'0',STR_PAD_LEFT);
            $row = kernel::database()->selectrow('select sp_bn from sdb_wms_spadjustmentdoc where sp_bn =\''.$sp_bn.'\'');
        }while($row);
        return $sp_bn;
    }
    
    /**
     * 店铺差价获取物料
     *
     * @param Void
     * @return String
     */
    function findmaterialbasic($supplier_id=null)
    {       
        $params = array(
                'title'=>'基础物料',
                'use_buildin_new_dialog' => false,
                'use_buildin_set_tag'=>false,
                'use_buildin_recycle'=>false,
                'use_buildin_export'=>false,
                'use_buildin_import'=>false,
                'use_buildin_filter'=>true,
                'base_filter' => $base_filter,
        );
        $this->finder('material_mdl_basic_material', $params);
    }

    function getmaterialbasic()
    {
        $basicMaterialObj = app::get('material')->model('basic_material');
        $omeExtOrdLib = kernel::single('ome_extint_order');
        $pro_id = $_POST['product_id'];

        $basicMaterialData= $basicMaterialObj->getList('*',array('bm_id' => $pro_id ));
        if (!empty($basicMaterialData))
        {
            foreach ($basicMaterialData as $k => $item)
            {
                $itm['product_id']=$item['bm_id'];
                $itm['material_bn']=$item['material_bn'];
                $itm['material_name']=$item['material_name'];
                $rows[]= $itm;

            }
        }
        echo "window.autocompleter_json=".json_encode($rows);
    }
    //保存备货通知单
    function doSave()
    {
        $this->begin('index.php?app=wms&ctl=admin_spadjustmentdoc&act=index');  
        $data=$_POST;
        $id=$_POST['id'];
        $begin = strtotime($data['begin_date']);
        $end = strtotime($data['end_date'])+86399;  
        if($begin>$end)
        {
            $this->end(false, app::get('base')->_('结束时间小于开始时间，请确认！'));
        } 
        $db = kernel::database();
        if(empty($id))
        {
            $sql="SELECT * from sdb_wms_spadjustmentdoc where begin_date<=$begin and $begin<end_date and shop_id='".$_POST['shop_id']."'";
        }else{
            $sql="SELECT * from sdb_wms_spadjustmentdoc where begin_date<=$begin and $begin<end_date and shop_id='".$_POST['shop_id']."' and id!='$id'";
        }
        $rows= $db->select($sql);
        if(!empty($rows))
        {
            $this->end(false, app::get('base')->_('开始时间已存在区间，请确认日期！'));
        }
        if(empty($id))
        {
            $sql1="SELECT * from sdb_wms_spadjustmentdoc where begin_date<=$end and $end<end_date and shop_id='".$_POST['shop_id']."'";
        }else{
            $sql1="SELECT * from sdb_wms_spadjustmentdoc where begin_date<=$end and $end<end_date and shop_id='".$_POST['shop_id']."' and id!='$id'";
        }
        $rows1= $db->select($sql1);
        if(!empty($rows1))
        {
            $this->end(false, app::get('base')->_('结束时间已存在区间，请确认日期！'));
        }
        if(empty($id))
        {
            $sql2="SELECT * from sdb_wms_spadjustmentdoc where begin_date>=$begin and $end>=end_date and shop_id='".$_POST['shop_id']."'";
        }else{
            $sql2="SELECT * from sdb_wms_spadjustmentdoc where begin_date>=$begin and $end>=end_date and shop_id='".$_POST['shop_id']."' and id!='$id'";
        }
        $rows2= $db->select($sql2);
        if(!empty($rows2))
        {
            $this->end(false, app::get('base')->_('该区间已重复定义，请确认日期！'));
        }

        $spdocMdl = app::get('wms')->model('spadjustmentdoc');
        $spdocMdlL = app::get('wms')->model('spadjustmentdoc_line');
        $delivery_ID = $_POST['delivery_ID'];
        $memo = $_POST['memo'];
        $operator = $_POST['operator'];
        if(empty($id))
        {
            $arr_order='';
            $arr_order['sp']['sp_bn']=$this->gen_id();
            $arr_order['sp']['remark']=$_POST['memo'];
            $arr_order['sp']['operator']=$_POST['operator'];
            $arr_order['sp']['shop_id']=$_POST['shop_id'];
            $arr_order['sp']['src_customer']=$_POST['src_customer'];
            $arr_order['sp']['booked_time']=strtotime($_POST['booked_time']);
            $arr_order['sp']['inter_time']=strtotime($_POST['inter_time']);
            $arr_order['sp']['create_time']=time();
            $arr_order['sp']['begin_date']=$begin;
            $arr_order['sp']['end_date']=$end;
            $res = $spdocMdl->insert($arr_order['sp']);

        }else
        {
            $res=$id;
            $data['shop_id'] =$_POST['shop_id'];
            $data['remark'] =$_POST['memo'];
            $data['booked_time'] =strtotime($_POST['booked_time']);
            $data['inter_time'] =strtotime($_POST['inter_time']);
            $data['begin_date'] =$begin;
            $data['end_date'] =$end;
            $data['src_customer']=$_POST['src_customer'];
            $data['id'] = $id;
            app::get('wms')->model('spadjustmentdoc')->save($data);
            kernel::database()->exec("delete from sdb_wms_spadjustmentdoc_line  where  spadjustmentdoc_id in(" . $id . ");");
        } 
        foreach ($delivery_ID as $key => $value)
        {
            $arr_line='';
            $arr_line['spl']['spadjustmentdoc_id']=$res;
            $arr_line['spl']['bn']=$value['material_bn'];
            $arr_line['spl']['product_name']=$value['material_name'];
            $arr_line['spl']['begin_date']=strtotime($value['begin_date']);
            $arr_line['spl']['end_date']=strtotime($value['end_date'])+86399;
            $arr_line['spl']['price']=$value['price'];
            $arr_line['spl']['diffprice']=$value['diffprice'];
            $arr_line['spl']['cod']=$value['cod'];
            $spdocMdlL->insert($arr_line['spl']);
            unset($arr_line);
            
        }
        $this->end(true, '已完成');
    }

    function editspadjustmentdoc()
    {
        $spadjustmentdocMdl = $this->app->model('spadjustmentdoc');
        $spadjustmentdoc_datas = $spadjustmentdocMdl->getList('*', array('id'=>$_GET['id']), 0, -1);

        
        $sql = 'SELECT shop_id,shop_bn,name FROM sdb_ome_shop WHERE leemantype=\'1\' ';
        $shop_datas = kernel::database()->select($sql);
        foreach ($shop_datas as $v) {
            $shop_data[$v['shop_id']] ='【'.$v['shop_bn'].'】'. $v['name'];
        }

        $this->pagedata['shop_data'] = $shop_data;
        $this->pagedata['spadjustmentdoc'] = $spadjustmentdoc_datas[0];
        $this->pagedata['spadjustmentdoc']['begin_date'] =date('Y-m-d',$spadjustmentdoc_datas[0]['begin_date']) ;
        $this->pagedata['spadjustmentdoc']['end_date'] =date('Y-m-d',$spadjustmentdoc_datas[0]['end_date']) ;
        $this->singlepage('admin/spadjustmentdoc/spdoc_edit.html');
    }

    function getEditProducts($po_id){
        if ($po_id == ''){
            $po_id = $_POST['p[0]'];
        }
        //$sql="SELECT * from sdb_wms_spadjustmentdoc_line  where spadjustmentdoc_id=".$po_id;
        $sql="SELECT id,spadjustmentdoc_id,bn,product_name,price,diffprice,cod,FROM_UNIXTIME(last_modify, '%Y-%m-%d %H:%i:%S') as last_modify,FROM_UNIXTIME(begin_date, '%Y-%m-%d') as begin_date,FROM_UNIXTIME(end_date, '%Y-%m-%d') as end_date from sdb_wms_spadjustmentdoc_line  where spadjustmentdoc_id=".$po_id;

        $db=kernel::database();
        $rows=$db->select($sql);  
        $i=0;
        foreach ($rows as $key => $value)
        {
            $items[$key]=$value;
            $items[$key]['product_id']=$i;    
            $items[$key]['material_bn']=$value['bn'];    
            $items[$key]['material_name']=$value['product_name'];
            $items[$key]['begin_date']=$value['begin_date'];
            $items[$key]['end_date']=$value['end_date'];
            $items[$key]['cod']=$value['cod'];
            $items[$key]['price']=$value['price'];
            $items[$key]['diffprice']=$value['diffprice'];

            $i=$i+1;
        }
        echo json_encode($items);
    }
    //审核
    function doapprove()
    {
        $this->updatestatus(1);
    }
    //弃审
    function dounapprove()
    {
        $this->updatestatus(0);
    }
    function updatestatus($is_approve)
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=wms&ctl=admin_spadjustmentdoc&act=index");
        $this->_request    = kernel::single('base_component_request');
        $order_info        = $this->_request->get_post();
        $db=kernel::database();
        $spdocMdl = $this->app->model('spadjustmentdoc');
        if ($order_info['isSelectedAll']=='_ALL_') 
        {
            foreach ($orders as $key_o => $order) 
            {
                $value = $order['id']; 
                $spdocdata=$spdocMdl->dump($value,"*");
                if($is_approve==1)
                {
                    if($spdocdata['status']!='unconfirmed'){
                        $this->end(false, $spdocdata['sp_bn'].'状态异常，审核失败！');
                    }

                    $db->exec("update sdb_wms_spadjustmentdoc set status='confirmed',last_modify='".time()."' where  id in(" . $value . ");");   
                }else if($is_approve==0)
                {
                    if($spdocdata['status']!='confirmed'){
                        $this->end(false, $spdocdata['sp_bn'].'状态异常，弃审失败！');
                    }
                    $db->exec("delete from sdb_wms_spadjustmentdoc_record  where  spadjustmentdoc_id in(" .$value . ");");
                    $db->exec("update sdb_wms_spadjustmentdoc set status='unconfirmed',last_modify='".time()."' where  id in(" . $value . ");");   
                }
                $this->end(true, '操作成功');
            }
        }else
        {
            $input = file_get_contents("php://input");
            $input_array = explode('&', $input);
            $number = count($input_array);
            if ($number > $max_input_vars) {
                $msg =  "多选不能超过系统表单最大提交数【".$max_input_vars."】条";
                $this->end(false, $msg);
            }
            foreach ($order_info['id'] as $key_o => $value)
            {   
                $spdocdata=$spdocMdl->dump($value,"*");
                if($is_approve==1)
                {
                    if($spdocdata['status']!='unconfirmed'){
                        $this->end(false, $spdocdata['sp_bn'].'状态异常，审核失败！');
                    }
                    $db->exec("update sdb_wms_spadjustmentdoc set status='confirmed',last_modify='".time()."' where  id in(" . $value . ");");   
                }else if($is_approve==0)
                {
                    if($spdocdata['status']!='confirmed'){
                        $this->end(false, $spdocdata['sp_bn'].'状态异常，弃审失败！');
                    }
                    $db->exec("delete from sdb_wms_spadjustmentdoc_record  where  spadjustmentdoc_id in(" .$value . ");");
                    $db->exec("update sdb_wms_spadjustmentdoc set status='unconfirmed',last_modify='".time()."' where  id in(" . $value . ");");   
                }
                $this->end(true, '操作成功');
            }
        }
        $this->end(true, '已完成');
    }
    //提交动作
    function doCreate()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=wms&ctl=admin_spadjustmentdoc&act=index");
        $this->_request = kernel::single('base_component_request');
        $postData = $this->_request->get_post();
        if ($postData['isSelectedAll'] == '_ALL_') {
            $this->end(false, '不可全选！');
        }
        if (count($postData['id']) > 1) 
        {
            $this->end(false, '请单条生成！');
        }
        //add by ldward 20181128生成明细
        $id=$postData['id'][0];
        $spdocMdl = $this->app->model('spadjustmentdoc');
        $spdata=$spdocMdl->dump($id,"*");
        if($spdata['status']!='confirmed')
        {   
            $this->end(false, '状态异常，无法生成明细！');
        }
        $spdocMdlL = $this->app->model('spadjustmentdoc_line');
        $spLinedata=$spdocMdlL->getList('*', array('spadjustmentdoc_id' => $id ));
        $cod = array(0 => '<',1=>'<=',2=>'=', );
        $db=kernel::database();
        $db->exec("delete from sdb_wms_spadjustmentdoc_record  where  spadjustmentdoc_id in(" . $id . ");");
        foreach ($spLinedata as $key => $value) 
        {
            // $sql="insert into sdb_wms_spadjustmentdoc_record(spadjustmentdoc_id,order_bn,createtime,bn,name,nums,price,divide_order_fee,diffprice,diffmny,last_modify)select ".$id." spadjustmentdoc_id,os.order_bn,os.createtime,its.bn,its.`name`,its.nums,its.price,its.divide_order_fee,".$value['diffprice']." diffprice,its.nums*".$value['diffprice']." diffmoney,".time()." last_modify from sdb_ome_orders os
            //     inner join sdb_ome_order_items its on os.order_id=its.order_id
            //     where os.shop_id='".$spdata['shop_id']."' and os.abnormal='false' and os.is_fail='false' and its.bn='".$value['bn']."' and its.price".$cod[$value['cod']].$value['price']." 
            //     and os.createtime between ".$spdata['begin_date']." and ".$spdata['end_date'];
            //
            $sql="INSERT into sdb_wms_spadjustmentdoc_record(spadjustmentdoc_id,bn,name,unit,price,nums,diffprice,diffmny,last_modify,begin_date,end_date)
                SELECT  ".$id." spadjustmentdoc_id,items.bn,items.product_name name,ext.unit,its.divide_order_fee  /its.nums price
                ,IFNULL(count(items.number),0) nums,
                ".$value['diffprice']." diffprice,IFNULL(sum(items.number),0)*".$value['diffprice']." diffmoney,".time()." last_modify
                ,".$value['begin_date'].",".$value['end_date']." 
                FROM  sdb_wms_deliverycomp a 
                inner join sdb_wms_deliverycomp_line b on a.id = b.deliverycomp_id
                inner join sdb_wms_deliverynote_line d on b.deliverynote_id = d.deliverynote_id
                inner join sdb_wms_delivery e on d.delivery_bn = e.delivery_bn
                inner join sdb_wms_delivery_items items on e.delivery_id=items.delivery_id
                inner JOIN sdb_ome_delivery od on ( e.outer_delivery_bn = od.delivery_bn )
                inner JOIN sdb_ome_delivery_order odo on ( od.delivery_id = odo.delivery_id )
                inner JOIN sdb_ome_orders os on (odo.order_id = os.order_id)
                inner join sdb_ome_order_items its on items.bn=its.bn and its.order_id=os.order_id
                inner JOIN sdb_material_basic_material_ext ext on items.product_id=ext.bm_id 
                inner join sdb_ome_shop f on e.shop_id=f.shop_id
                where a.deliverycomp_time BETWEEN ".$spdata['begin_date']." and ".$spdata['end_date']." and f.shop_id='".$spdata['shop_id']."'  and its.bn='".$value['bn']."' and its.divide_order_fee / its.nums ".$cod[$value['cod']].$value['price']." 
                    and os.createtime BETWEEN ".$value['begin_date']." and ".$value['end_date'] ." 
                    and its.delete = 'false'
                group by items.bn,items.product_name,ext.unit,its.divide_order_fee / its.nums";
            $db->exec($sql);

            //退货
            $reshipsql="INSERT into sdb_wms_spadjustmentdoc_record(spadjustmentdoc_id,bn,name,unit,price,nums,diffprice,diffmny,last_modify,begin_date,end_date)
                select ".$id." spadjustmentdoc_id,its.bn,its.product_name,ext.unit,its.price,-sum(its.num) nums,
                ".$value['diffprice']." diffprice,-IFNULL(sum(its.num),0)*".$value['diffprice']." diffmoney,".time()." last_modify
                ,".$value['begin_date'].",".$value['end_date']."  
                from sdb_ome_reship rp
                inner join sdb_ome_reship_items its on rp.reship_id=its.reship_id
                inner JOIN sdb_material_basic_material_ext ext on its.product_id=ext.bm_id 
                inner join sdb_ome_orders os on rp.order_id = os.order_id 
                where rp.send_status='1' and rp.inter_time between ".$spdata['begin_date']." and ".$spdata['end_date']." and rp.shop_id='".$spdata['shop_id']."' and its.num>0 and its.bn='".$value['bn']."' and its.price".$cod[$value['cod']].$value['price']." 
                    and os.createtime BETWEEN ".$value['begin_date']." and ".$value['end_date'] ." 
                group by its.bn,its.product_name,ext.unit,its.price";

            $db->exec($reshipsql);
        }
        $db->exec("update sdb_wms_spadjustmentdoc set status='created',last_modify='".time()."' where  id in(" . $id . ");"); 
        $this->end(true, '已完成');
    }
    //取消动作
    function doCancel()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=wms&ctl=admin_spadjustmentdoc&act=index");
        $this->_request = kernel::single('base_component_request');
        $postData = $this->_request->get_post();
        if ($postData['isSelectedAll'] == '_ALL_') {
            $this->end(false, '不可全选！');
        }
        if (count($postData['id']) > 1) 
        {
            $this->end(false, '请单条取消生成！');
        }
        //add by ldward 20181128生成明细
        $id=$postData['id'][0];
        $spdocMdl = $this->app->model('spadjustmentdoc');
        $spdata=$spdocMdl->dump($id,"*");
        if($spdata['status']!='created')
        {   
            $this->end(false, '状态异常，无法取消生成！');
        }
        $db=kernel::database();
        $db->exec("delete from sdb_wms_spadjustmentdoc_record  where  spadjustmentdoc_id in(" . $id . ");");
        $db->exec("update sdb_wms_spadjustmentdoc set status='confirmed',last_modify='".time()."' where  id in(" . $id . ");"); 
        $this->end(true, '取消成功！');
    }
    //过数
    function doConfirm()
    {
        
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=wms&ctl=admin_spadjustmentdoc&act=index");
        $this->_request = kernel::single('base_component_request');
        $postData = $this->_request->get_post();
        if ($postData['isSelectedAll'] == '_ALL_') {
            $this->end(false, '不可全选！');
        }
        if (count($postData['id']) > 1) 
        {
            $this->end(false, '请单条同步！');
        }
        $id=$postData['id'][0];
        $spdocMdl = $this->app->model('spadjustmentdoc');
        $spdata=$spdocMdl->dump($id,"*");
        if($spdata['status']!='created')
        {   
            $this->end(false, '状态异常，无法执行过数操作！');
        }
        if($spdata['status']=='sync')
        {
            $this->end(false, '状态已为同步，无法执行过数操作！');
        }
        $shopdata=app::get('ome')->model('shop')->dump($spdata['shop_id'],'*');
        $sql="SELECT f.shop_type,f.shop_bn,rd.bn,rd.diffprice,rd.price,rd.unit,sum(rd.nums) nums 
            from sdb_wms_spadjustmentdoc sp 
            inner join sdb_wms_spadjustmentdoc_record rd on sp.id=rd.spadjustmentdoc_id
            inner join sdb_ome_shop f on sp.shop_id=f.shop_id 
            where sp.id=".$id."
            group by f.shop_type,f.shop_bn,rd.bn,rd.diffprice,rd.price,rd.unit";
        $rows = kernel::database()->select($sql);
        foreach ($rows as $key => $value) 
        {   
            $salesPlatfrom = '其他';
            if ($value['shop_type'] != '') {
                $salesPlatfrom = ome_shop_type::shop_name($value['shop_type']);
            }
            $line[] = array(
                    'parmItemID' => $value['bn'],
                    'parmPlatform' => $salesPlatfrom,
                    'parmSalesPriceNew' => $value['diffprice'],
                    'parmSalesPriceOrg' => $value['price'],
                    'parmSalesQty' => $value['nums'],
                    'parmSalesUnit' => $value['unit'],
                    'parmShop' => $value['shop_bn'],);
        }
        $result = array(
                    'parmFormCustAccount' =>$shopdata['AXCustomer'],
                    'parmID' =>$spdata['sp_bn'],
                    'parmNote' =>$spdata['remark'],
                    'parmToCustAccount' =>$spdata['src_customer'],
                    'parmTransdate' =>Date('Y-m-d',$spdata['booked_time']), 
                    'PromotionalDifferenceLine' =>$line, );
        
        try 
        {
            date_default_timezone_set("PRC");
            ini_set('soap.wsdl_cache_enabled', "0"); //关闭wsdl缓存
            ini_set('default_socket_timeout', 500);
            $param['json'] = json_encode($result);//json
            $param['company'] = "1101";

            if(WITH_QIMEN){
                 $res=kernel::single('erpapi_rpc_qimen')->call('PromotionalDifference',$param);
                 $res=json_decode($res,1);
            }else{
                $webservice_url = HOST_AXToOMs;
                $client = new SoapClient($webservice_url);
                $res = $client->__soapCall('PromotionalDifference', array('parameters' => $param));
                $res['response']['data'] = $res->PromotionalDifferenceResult;
                //var_dump($res->CreateSalesOrderResult);
            }

            $arr = json_decode($res['response']['data'], '1');    
        
            if ($arr['Code']=='1') 
            {
                $data['status'] ='sync';
                $data['msg']=$arr['Msg'];
                $data['id'] = $id;
                app::get('wms')->model('spadjustmentdoc')->save($data);
                $this->end(true, '同步成功');
            }elseif($arr['Code']=='0')
            {
                //OMS单号：201812121213008061,编号201812121213008061已存在!
                if(strpos($arr['Msg'],$spdata['sp_bn']."已存在") !== false)
                { 
                    $data['status'] ='sync';
                    $data['msg']=$arr['Msg'];
                    $data['id'] = $id;
                    app::get('wms')->model('spadjustmentdoc')->save($data); 
                }else{
                    $this->end(false,$arr['Msg']);          
                }
            }
        } catch (Exception $e) 
        {
            $this->end(false,$e->getMessage());   
        }
        $this->end(true, '同步成功');
    }
    //删除动作
    function doDelete()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=wms&ctl=admin_spadjustmentdoc&act=index");
        $this->_request    = kernel::single('base_component_request');
        $order_info        = $this->_request->get_post();

        $spMdl = $this->app->model('spadjustmentdoc');

        if ($order_info['isSelectedAll']=='_ALL_') 
        {
            foreach ($orders as $key => $order) 
            {
                $value = $order['id'];
                $spdata = $spMdl->dump($value,"*");
                if ($spdata['status'] == 'unconfirmed') 
                {
                    $spMdl->db->exec("delete from sdb_wms_spadjustmentdoc_line where spadjustmentdoc_id in(".$value . ");");
                    $spMdl->db->exec("delete from sdb_wms_spadjustmentdoc  where  id in(" . $value . ");");
                } else {
                    $this->end(false, '过数单号【' . $spdata['sp_bn'] . '】状态已同步，删除失败！');
                }
            }
        } else {
            $input = file_get_contents("php://input");
            $input_array = explode('&', $input);
            $number = count($input_array);
            if ($number > $max_input_vars) {
                $msg =  "多选不能超过系统表单最大提交数【".$max_input_vars."】条";
                $this->end(false, $msg);
            }
            foreach ($order_info['id'] as $key_o => $value) 
            {
                $spdata = $spMdl->dump($value,"*");

                if ($spdata['status'] == 'unconfirmed') 
                {
                    $spMdl->db->exec("delete from sdb_wms_spadjustmentdoc_line where spadjustmentdoc_id in(" . $value . ");");
                    $spMdl->db->exec("delete from sdb_wms_spadjustmentdoc where id in(" . $value . ");");
                } else {
                    $this->end(false, '过数单号【' . $spdata['sp_bn'] . '】状态已同步，删除失败！');
                }
            }
        }
        $this->end(true, '已完成');
    }
}



